package com.tensquare.friend.interceptor;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    //1.添加过滤器--得到请求头的数据并转换为claims,放到request作用域中
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String header = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(header) && header.startsWith("Bearer ")){
            String token = header.substring(7);
            Claims claims = jwtUtils.getClaims(token);
            request.setAttribute("claims",claims);
        }
        return true;
    }
}
